import * as commonUtil from '@/utils/commonUtil'
import loginRequest from '@/api/login'
import {
  getIndexAll
} from "@/api/homeService"; //首页所有信息
import {
  collegeQueryAll
} from "@/api/user"; //学院以及专业信息
import user from '../api/user'
// 自动重新连接ws插件
import ReconnectingWebSocket from 'reconnecting-websocket'
// import PersistedState from 'vuex-persistedstate'
export const state = () => ({
  collegeAndMajor: [], //学院以及专业信息
  activitieList: [], //活动信息
  userInfo: '',
  isY: true,
  isJoin: false,
  isLogin: false,
  webSocket: null, // webSocket对象,
  nowTime: ""
})

//   export const plugins=[ PersistedState({ storage: window.sessionStorage })]
export const getters = {
  getCollegeAndMajor: state => state.collegeAndMajor,
  getActivitieList: state => state.activitieList,
  getIsLogin(state) {
    return state.isLogin
  },
  getUserInfo(state) {
    return state.userInfo
  },
  getIsJoin(state) {
    return state.isJoin
  },
  getNowTime(state) {
    return state.nowTime
  }
}

export const mutations = {
  setIsLogin(state, data) {
    state.isLogin = data
  },
  /**
   * 初始化webSocket对象
   * @param {*} state
   * @param {*} url
   */
  setWebSocket(state, url) {
    let webSocket = null
    webSocket = new ReconnectingWebSocket(url)
    // state.webSocket = webSocket
    // 连接成功
    state.webSocket.onopen = function () {
      console.log('连接成功')
    }
    // 监听消息
    state.webSocket.onmessage = function (message) {
      console.log('收到消息' + message.data)
    }
    // 监听错误
    state.webSocket.onerror = function (e) {
      console.log('错误连接：' + e)
    }
    // 监听关闭
    state.webSocket.onclose = function (e) {
      console.log('关闭连接：' + e)
    }
  },
  /**
   * 关闭webSocket
   * @param {*} state
   */
  closeWebSocket(state) {
    console.log('网络断开，关闭连接')
    state.webSocket.close()
  },
  /**
   * 发送消息
   * @param {*} state
   * @param {*} message
   */
  webSocketSend(state, message) {
    // console.log('ws发送！')
    if (typeof message !== 'string') {
      message = JSON.stringify(message)
    }
    state.webSocket.send(message)
  },
  //更新活动状态信息
  SET_ACTIVITY_STATUS(state, {
    activityId,
    status
  }) {
    const index = state.activitieList.findIndex(item => item.id === activityId);
    if (index !== -1) {
      state.activitieList[index].status = status;
    }
  },
  setActivitieList(state, list) {
    state.activitieList = list;
  },
  setCollegeInfo(state, list) {
    state.collegeAndMajor = list
  },
  //更新用户信息
  updateUserInfo(state, userInfo) {
    state.userInfo = userInfo
    if (process.client) {
      localStorage.setItem('userId', userInfo.id);
    }
  },
  //修改用户头像
  updateUserAvatar(state, avatar) {
    state.userInfo.avatar = avatar
  },
  //更新用户协会成员状态
  updateUserIsJoin(state, isJoin) {
    state.isJoin = isJoin
  },
  //退出登录的时候清空所有数据
  wipeData(state) {
    state.userInfo = ''
    state.isJoin = ''
    if (process.client) {
      localStorage.removeItem('userId');
    }
  },
  //y轴是否滑动过
  updateY(state, isY) {
    state.isY = isY
  },
  updateNowTime(state, nowTime) {
    state.nowTime = nowTime
  },
}

export const actions = {
  login({
    state,
    commit
  }, data) {
    return new Promise((resolve, reject) => {
      loginRequest.login(data.params).then((res) => {
        if (res.code === 20000) {
          //存储token到本地缓存
          if (process.client) {
            commonUtil.setStore('token', res.data.token);
          }
          commit('setIsLogin', true)
          resolve(res)
        } else {

          // this.$message.error(res.message);
          reject(res)
        }
      }).catch((err) => {
        reject(err)
      })
    })
  },
  //退出登录
  logout({
    commit
  }) {
    commit('wipeData')
    // userInfo: '',
    // isJoin: false,
  },

  // 初始化连接
  webSocketInit({
    commit
  }) {
    const url = 'ws://1.14.161.60:6720/api/ws'
    commit('setWebSocket', url)
  },
  //根据token查询用户信息
  queryUser({
    state,
    commit
  }) {
    return new Promise((resolve, reject) => {
      loginRequest.getLoginInfo().then((res) => {
        if (res.data.code === 20000 && res.data.data.user) {
          commit('updateUserInfo', res.data.data.user)
          commit('updateUserIsJoin', res.data.data.isJoin)
          resolve(res)
        } else {
          reject(res)
        }
      }).catch((err) => {
        reject(err)
      })
    })
  },
  queryActivity({
    state,
    commit
  }) {
    return new Promise((resolve, reject) => {
      getIndexAll().then((res) => {
        if (res.code === 20000) {
          commit('setActivitieList', res.data.activitieList)
          resolve(res)
        } else {
          reject(res)
        }
      }).catch((err) => {
        reject(err)
      })
    })
  },
  queryCollege({
    state,
    commit
  }) {
    return new Promise((resolve, reject) => {
      collegeQueryAll().then((res) => {
        if (res.data.code === 20000) {
          commit('setCollegeInfo', res.data.data.collegeAndMajor)
          resolve(res)
        } else {
          reject(res)
        }
      }).catch((err) => {
        reject(err)
      })
    })
  },
  
}
